#include "UserDao.h"
#include <sqlite3.h>
#include <stdio.h>

void addUser(User* user){
    //定义一个sqlite3对象
    sqlite3 *db=NULL;
    //打开数据库
    int ret=sqlite3_open("/home/vm/CC_ads/test.db",&db);
    if (ret!=0)
    {
        perror("sqlite db open fail\n");
        return;
    }
    //拼接sql
    char sql[256];
    sprintf(sql,"insert into t_user(id,name) values(%d,'%s');",user->id,user->name);
    char* errorMsg;
    sqlite3_exec(db,sql,NULL,NULL,&errorMsg);
    if (errorMsg!=NULL)
    {
        printf("insert sql exec fail,reason:%s\n",errorMsg);
    }else
    {
        printf("insert sql exec success\n");
    }
    
    //关闭sqlite
    sqlite3_close(db);
}

void getOne(int id){
    //定义一个sqlite3对象
    sqlite3 *db=NULL;
    //打开数据库
    int ret=sqlite3_open("/home/vm/CC_ads/test.db",&db);
    if (ret!=0)
    {
        perror("sqlite db open fail\n");
        return;
    }
    //拼接sql
    char sql[256]="select * from t_user";
    
    char* errorMsg;
    char** pResult;
    int nRow=0;
    int nCol=0;

    ret=sqlite3_get_table(db,sql,&pResult,&nRow,&nCol,&errorMsg);
    if (ret!=SQLITE_OK)
    {
        printf("queyr fail,%s\n",errorMsg);
    }else
    {
        /* 处理结果集 */
        printf("共有%d行%d列数据\n",nRow,nCol);
        int i,j;
        for ( i = 0; i < nRow; i++)
        {
            for ( j = 0; j < nCol; j++)
            {
                int temp=i*nCol+j;
                printf("%s\t",pResult[temp]);
            }
            printf("\n");
        }
        
    }
    
    //关闭
    sqlite3_close(db);
}